package com.hay.cart.service;

import com.hay.auth.common.entity.UserInfo;
import com.hay.cart.Interceptor.LoginInterceptor;
import com.hay.cart.client.GoodsClient;
import com.hay.cart.pojo.Cart;
import com.hay.common.utils.JsonUtils;
import com.hay.item.pojo.Sku;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @title: CartService
 * @Author HuangYan
 * @Date: 2020/8/5 23:14
 * @Version 1.0
 */
@Service
public class CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private GoodsClient goodsClient;

    private static final String KEY_PREFIX = "leyou:cart:";

    /**
     * 新增购物车
     * @param cart
     */
    public void addCart(Cart cart) {

        // 获取用户信息
        UserInfo userInfo = LoginInterceptor.getUserInfo();

        String key = KEY_PREFIX + userInfo.getId().toString();

        // 判断redis数据库中是否存在此此用户
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(key);

        // 将传入cart中的skuId和num进行暂存
        Long skuId = cart.getSkuId();
        Integer num = cart.getNum();
        
        // 判断hashOps里是否存在skuId这个key
        Boolean aBoolean = hashOps.hasKey(skuId.toString());
        if (aBoolean){
            // 存在则更新数量即可
            String jsonCart = hashOps.get(skuId.toString()).toString();
            // 通过工具类，将json字符串类型转换为Cart
            cart = JsonUtils.parse(jsonCart, Cart.class);
            // 更新数量
            cart.setNum(cart.getNum() + num);

        } else {
            // 不存在则查询数据
            cart.setUserId(userInfo.getId());
            Sku sku = goodsClient.getSkuBySkuId(skuId);
            // 设置cart的值
            cart.setTitle(sku.getTitle());
            cart.setImage(StringUtils.isBlank(sku.getImages()) ? "" : StringUtils.split(sku.getImages(),",")[0]);
            cart.setOwnSpec(sku.getOwnSpec());
            cart.setPrice(sku.getPrice());
        }
            hashOps.put(skuId.toString(), JsonUtils.serialize(cart));
    }

    /**
     * 查询购物车
     * @return
     */
    public List<Cart> queryCarts() {

        // 在TreadLocal中获取登陆用户信息
        UserInfo userInfo = LoginInterceptor.getUserInfo();

        // 判断用户是否以已经存在购物车
        String key = KEY_PREFIX + userInfo.getId();
        if (!redisTemplate.hasKey(key)){
            return null;
        }
        // 存在这获取购物车集合
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(key);
        // 购物车中如果没有商品，则返回空
        if (CollectionUtils.isEmpty(hashOps.values())){
            return null;
        }
        List<Object> jsonCarts = hashOps.values();
        // 遍历购物车集合，对每个商品进行序列化
        List<Cart> carts = jsonCarts.stream().map(jsonCart -> JsonUtils.parse(jsonCart.toString(), Cart.class)).collect(Collectors.toList());
        return carts;

    }

    /**
     * 修改商品数量
     * @param cart
     */
    public void editCartNum(Cart cart) {
        UserInfo userInfo = LoginInterceptor.getUserInfo();

        String key = KEY_PREFIX + userInfo.getId();

        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(key);
        // 暂存修改的数量
        Integer num = cart.getNum();

        String jsonCart = hashOps.get(cart.getSkuId().toString()).toString();

        cart = JsonUtils.parse(jsonCart, Cart.class);
        cart.setNum(num);

        hashOps.put(cart.getSkuId().toString(), JsonUtils.serialize(cart));
    }

    /**
     * 删除购物车中的商品
     * @param skuId
     * @return
     */
    public void deleteCart(Long skuId) {
        UserInfo userInfo = LoginInterceptor.getUserInfo();

        String key = KEY_PREFIX + userInfo.getId();

        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(key);

        hashOps.delete(skuId.toString());
    }
}
